package com.xuetao.demo.cartoonface.controller;

import com.xuetao.demo.cartoonface.dto.ResponseDTO;
import com.xuetao.demo.cartoonface.util.CartoonityUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@Controller
public class AvatarController {

    @Value("${picture.file}")
    private String pictureFilePath;

    @RequestMapping("/")
    public String toPage() {
        return "cartoon";
    }

    @RequestMapping("/avatar/upload")
    @ResponseBody
    public ResponseDTO upload(MultipartFile avatarFile) {
        if (avatarFile.isEmpty()) {
            return ResponseDTO.fail("请选择图片");
        }

        String fileName = String.valueOf(System.currentTimeMillis());
        try {
            avatarFile.transferTo(new File(pictureFilePath + fileName));
            //卡通画处理图片
            CartoonityUtil.processPicture(pictureFilePath + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseDTO.fail("图像处理失败");
        }

        return ResponseDTO.success(fileName);
    }

    @RequestMapping("/avatar/loadAvatar/{fileName}")
    public void loadAvatar(@PathVariable("fileName") String fileName, HttpServletResponse response) {
        try {
            FileInputStream fis = new FileInputStream(pictureFilePath + fileName);
            response.setContentType("image/png");
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] buff = new byte[1024];
            int length = -1;
            while (-1 != (length = fis.read(buff))) {
                outputStream.write(buff, 0, length);
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


}
